<!-- 聊天 -- 入口 -->
<template>
  <div class="chat_container">
    ceshi
    <!-- <el-input v-model="sendText" placeholder="请输入内容"></el-input> -->
    <!-- <el-button type="primary" @click="sendMsg">发送</el-button> -->
    <div id="my_container"></div>
    <div id="you_container"></div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      nim: "",
      toUser: {
        // 发给谁
        account: "aa",
        token: "123456",
        logo: "",
        name: ""
      },
      myUser: {
        // 自己的
        account: "bb",
        token: "123456",
        logo: ""
      },
      sendText: "",
      userList: [], // 曾经有过对话的会话列表

      netcall: null,
      Netcall: null
    };
  },
  components: {},
  mounted() {
    this.content();
  },
  methods: {
    initVideo() {
      console.log('=======', WebRTC)
      this.Netcall = WebRTC;
      NIM.use(this.Netcall)
      this.netcall = this.Netcall.getInstance({
        nim: this.nim,
        container: document.getElementById("my_container"),
        remoteContainer: document.getElementById("you_container"),
        chromeId: "",
        debug: true
      })
      console.log(this.netcall)
      console.log('----------',this.netcall.isSupportWebrtc())
      this.callYou2()
    },
    callYou2() {
      this.netcall.call({
        type: this.Netcall.NETCALL_TYPE_VIDEO,
        webrtcEnable: true,
        account: 'aa',
        pushConfig: {
          enable: true,
          needBadge: true,
          needPushNick: true,
          pushContent: '',
          custom: '测试自定义数据',
          pushPayload: '',
          sound: '',
          forceKeepCalling: 0
        },
        sessionConfig: {
          videoQuality: this.Netcall.CHAT_VIDEO_QUALITY_NORMAL,
          videoFrameRate: this.Netcall.CHAT_VIDEO_FRAME_RATE_15,
          videoBitrate: 0,
          recordVideo: false,
          recordAudio: false,
          highAudio: false,
          bypassRtmp: false,
          rtmpUrl: '',
          rtmpRecord: false,
          splitMode: this.Netcall.LAYOUT_SPLITLATTICETILE
        }
      }).then(obj => {
        console.log('成功发起呼叫')
      }).catch(err => {
        if (err.event.code == 11001) console.log('被叫不在线', err)
      })

      // 设置超时计时器
      let callTimer = setTimeout(function() {
        if (!netcall.callAccepted) {
          console.log('超时未接听, hangup');
          hangup();
        }
      }, 1000 * 30);
    },
    callYou() { // 呼叫某用户
      console.log('呼叫用户', this.netcall)
      let obj = {
        account: 'aa',
        type: 1,
        channelId: 10
      }

      // 是否被叫中
      let beCalling = false;
      // 呼叫类型
      let type = null;
      // 被叫信息
      let beCalledInfo = null;
      // 是否正忙
      let busy = false;
      // 开启监听
      this.netcall.on("beCalling", function(obj) {
        console.log('监听')
        console.log("on beCalling", obj);
        const channelId = obj.channelId;
        // 被叫回应主叫自己已经收到了通话请求
        this.netcall.control({
          channelId: channelId,
          command: this.Netcall.NETCALL_CONTROL_COMMAND_START_NOTIFY_RECEIVED
        });
        // 只有在没有通话并且没有被叫的时候才记录被叫信息, 否则通知对方忙并拒绝通话
        if (!this.netcall.calling && !beCalling) {
          type = obj.type;
          beCalling = true;
          beCalledInfo = obj;
        } else {
          if (this.netcall.calling) {
            busy = this.netcall.notCurrentChannelId(obj);
          } else if (beCalling) {
            busy = beCalledInfo.channelId !== channelId;
          }
          if (busy) {
            this.netcall.control({
              channelId: channelId,
              command: this.Netcall.NETCALL_CONTROL_COMMAND_BUSY
            });
            // 拒绝通话
            this.netcall.response({
              accepted: false,
              beCalledInfo: obj
            });
          }
        }
      });
    },
    acceptCall(obj) { // 被叫接受的通知
      this.netcall.on('callAccepted', function(obj) {
        console.log('on callAccepted', obj);
        // 如果呼叫之前，启动了超时倒计时，这里可以取消呼叫倒计时
        clearCallTimer();
        // 可以开启音视频连接操作。。。
      })
    },
    refuseCall(obj) { // 被叫拒绝的通知
      this.netcall.on('callRejected', function(obj) {
        console.log('on callRejected', obj);
        // 如果呼叫之前，启动了超时倒计时，这里可以取消呼叫倒计时
        clearCallTimer();
        // 挂断
        hangup();
        // 做清理工作
        resetWhenHangup();
      });
    },






    sendMsg() {
      var msg = this.nim.sendText({
        scene: "p2p",
        to: "aa",
        text: this.sendText,
        done(err, msg) {
          console.log(err, msg);
        }
      });
    },
    content() {
      // 建立im连接
      this.nim = NIM.getInstance({
        appKey: "2b70cec80ec40626d76df0539e87bfb1",
        account: this.myUser.account,
        token: this.myUser.token,
        customTag: "tag",
        onconnect: this.onConnect, // 连接建立成功
        onerror: this.onError, // 建立失败
        onwillreconnect: this.onWillReconnect, // 即将重连
        ondisconnect: this.onDisconnect, // 断开连接
        onloginportschange: this.onLoginPortsChange, // 多端登录状态变化
        onsessions: this.onSessions, // 同步最近会话列表
        onupdatesession: this.onUpdateSession, // 更新会话 -- 发送/接收/重置
        onsyncdone: this.onSyncDone, // 数据同步完成
        onsysmsg: this.onSysMsg,
        oncustomsysmsg: this.onCustomSysMsg
      });
    },
    onConnect(msg) {
      console.log("connect", msg);
      this.initVideo();
    },
    onError(msg) {
      console.log("error", msg);
      window.location.reload();
    },
    onWillreconnect(msg) {
      console.log("onWillreconnect", msg);
    },
    onDisconnect(msg) {
      console.log("onDisconnect", msg);
      this.imLog ? "" : this.$alert("您的账号已在其他设备登录");
    },
    onLoginPortsChange(msg) {
      console.log("onLoginPortsChange", msg);
    },
    onSessions(msg) {
      console.log("onSessions", msg);
      this.userList = msg;
    },
    onUpdateSession(msg) {
      // 更新信息 -- 接收消息的时候触发
      console.log("onUpdateSession", msg);
      if (this.isFirst != 4) {
        if (msg && msg.lastMsg && msg.lastMsg.from != this.myUser.account) {
          this.showMsgData.push(msg.lastMsg);
          setTimeout(() => {
            this.setScrllTop();
          }, 100);
        }
      }
    },
    onSyncDone(msg) {}
  }
};
</script>
<style lang="scss" scoped>
</style>